<template>
  <view class="add-address">
    <div class="uForm">
      <u-form :border-bottom="false" :model="form" ref="uForm" :error-type="['toast']" :rule="rules">
        <u-form-item class="border" label="门店名称" label-width="130" prop="nickName">
          <u-input v-model="form.nickName" clearable placeholder="填写名称与门店牌匾名称一致" />
        </u-form-item>
		<u-form-item class="border" label="门头照" label-width="130" prop="face">
			<u-avatar :src="src" mode="square" size="200" ></u-avatar>
			<u-upload  :header="header" :action="action" @on-uploaded="onUploaded" :source-type="sourcetype"  :maxCount="1" :previewFullImage="true" :show-progress="false"></u-upload>
		</u-form-item>
		<u-form-item label="经营类型" label-width="130" prop="business">
          <u-input v-model="business" type="select" @click="showBusiness" placeholder="请选择经营类型" />
        </u-form-item>
        <u-form-item label="联系人" label-width="130" prop="contacts">
          <u-input v-model="form.contacts"  placeholder="请输入真实的姓名" />
        </u-form-item>
		<view class="selectAddress" @click="clickUniMap">
		  选择门店地址
		</view>
        <u-form-item label="所在区域" label-width="130" prop="___path">
          <u-input v-model="form.___path" type="select" @click="showPicker" placeholder="请选择所在地区" />
        </u-form-item>
        <u-form-item class="detailAddress" label="详细地址" label-width="130" prop="detail">
          <u-input type="textarea" v-model="form.detail" maxlength="100" height="100" placeholder="街道楼牌号等" />
        </u-form-item>
        <u-form-item label="最早收货" label-width="130" prop="earliest">
		  <u-input v-model="form.earliest" :type="type"  @click="showTime(1)" placeholder="请选择时间"/>
        </u-form-item>
		<u-form-item label="最晚收货" label-width="130" prop="atlatest">
		  <u-input v-model="form.atlatest" :type="type"  @click="showTime(2)" placeholder="请选择时间"/>
		</u-form-item>
        <div class="saveBtn" @click="save">创建门店</div>
      </u-form>
	  <u-select v-model="businessShow" mode="mutil-column-auto" value-name="id" label-name="name" :list="businesslist" @confirm="businessConfirm"></u-select>
	  <u-picker  title="请选择时间" v-model="show" mode="time" @confirm="timePickerConfirm" @cancel="timePickerCancel" :params="params"></u-picker>
      <m-city :provinceData="list" headTitle="区域选择" ref="cityPicker" @funcValue="getpickerParentValue" pickerSize="4">
      </m-city>
	   <u-toast ref="uToast" />
      <uniMap v-if="mapFlag" @close="closeMap" @callback="callBackAddress" />
    </div>
  </view>
</template>
<script>
import city from "@/components/m-city/m-city.vue";
import storage from "@/utils/storage.js";
import { upload } from "@/api/common.js";
import uniMap from "@/components/uniMap";
import { saveUserExtra,getBusinessAll } from "@/api/members";
import permision from "@/js_sdk/wa-permission/permission.js";
export default {
  components: {
    "m-city": city,
    uniMap,
  },
  onShow() {
    // 判断当前系统权限定位是否开启
  },
  methods: {
    // 关闭地图
    closeMap() {
      this.mapFlag = false;
    },
    // 打开地图并访问权限
    clickUniMap() {
      // #ifdef APP-PLUS
      if (plus.os.name == "iOS") {
        // ios系统
        permision.judgeIosPermission("location")
          ? (this.mapFlag = true)
          : this.refuseMap();
      } else {
        // 安卓
        this.requestAndroidPermission(
          "android.permission.ACCESS_FINE_LOCATION"
        );
      }
      // #endif

      // #ifndef APP-PLUS
      this.mapFlag = true;
      // #endif
    },

    // 如果拒绝权限 提示区设置
    refuseMap() {
      uni.showModal({
        title: "温馨提示",
        content: "您已拒绝定位,请开启",
        confirmText: "去设置",
        success(res) {
          if (res.confirm) {
            //打开授权设置
            // #ifndef MP-WEIXIN
            uni.getSystemInfo({
              success(res) {
                if (res.platform == "ios") {
                  //IOS
                  plus.runtime.openURL("app-settings://");
                } else if (res.platform == "android") {
                  //安卓
                  let main = plus.android.runtimeMainActivity();
                  let Intent = plus.android.importClass(
                    "android.content.Intent"
                  );
                  let mIntent = new Intent("android.settings.ACTION_SETTINGS");
                  main.startActivity(mIntent);
                }
              },
            });
            // #endif
          }
        },
      });
    },

    // 获取安卓是否拥有地址权限
    async requestAndroidPermission(permisionID) {
      var result = await permision.requestAndroidPermission(permisionID);
      if (result == 1) {
        this.mapFlag = true;
      } else {
        this.refuseMap();
      }
    },
	//获取所有的经营类型
	getBusinessData(){
		getBusinessAll().then((res) => {
			if (res.data.success) {
				this.businesslist = res.data.result;
			}
		});
	},
    // 选择地址后数据的回调
    callBackAddress(val) {
	  uni.showLoading({
		title: "加载中",
	  });
      if (val.regeocode && val) {
        let address = val.regeocode;
		// console.log(address);
		// console.log(val);
        this.form.detail = address.formatted_address; //地址详情
		this.form.city = address.addressComponent.city;
        this.form.___path = val.data.result.name;
        this.form.consigneeAddressIdPath = val.data.result.id; // 地址id分割
        this.form.consigneeAddressPath = val.data.result.name; //地址名称， '，'分割
        this.form.lat = val.latitude; //纬度
        this.form.lon = val.longitude; //经度
         uni.hideLoading();
      }

      this.mapFlag = !this.mapFlag; //关闭地图
    },

    // 保存当前 地址
    save() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
			delete this.form.___path;
			console.log(this.form);
			let params = JSON.parse(JSON.stringify(this.form));
			saveUserExtra(params).then((res) => {
			  if (res.statusCode == 200) {
				 storage.setUserInfo(res.data.result);
				 storage.setHasLogin(true);
				 storage.setAutoCp(0)
				 // 登录成功
				 uni.showToast({
				 	title: "登录成功!",
				 	icon: "none",
				 });
				uni.switchTab({
					url: "/pages/tabbar/home/index",
				});
			  }
			});
        }
      });
    },
	//时间选择器
	timePickerConfirm(tex){
		if(this.time == '0') {
			return;
		}else if(this.time == '1'){
			if(this.form.atlatest){
				let date1 = new Date('2020-10-23 '+tex.hour+":"+tex.minute);
				let date2 = new Date('2020-10-23 '+this.form.atlatest);
				if(date1.getTime() > date2.getTime() || date1.getTime() == date2.getTime()){
					this.$refs.uToast.show({
						duration:3500,
						title: '最早收货时间不能大于最晚收货时间',
						type: 'error'
					})
					return;
				}
			}
			this.form.earliest = tex.hour+":"+tex.minute
		}else{
			if(this.form.earliest){
				let date1 = new Date('2020-10-23 '+tex.hour+":"+tex.minute);
				let date2 = new Date('2020-10-23 '+this.form.earliest);
				if(date1.getTime() < date2.getTime() || date1.getTime() == date2.getTime()){
					this.$refs.uToast.show({
						duration:3500,
						title: '最晚收货时间不能小于最早收货时间',
						type: 'error'
					})
					return;
				}
			}
			this.form.atlatest = tex.hour+":"+tex.minute
		}
	},
	businessConfirm(e){
		this.business = e[e.length-1].label;
		let businessId = [];
		e.forEach((item, index) => {
			businessId.push(item.value);
		});
		this.form.business = businessId.join();
	},
	timePickerCancel(){
		this.time = '0';
	},
	onUploaded(lists) {
	  let images = [];
	  lists.forEach((item) => {
	    images.push(item.response.result);
	  });
	  this.form.face = images[0];
	},
    // 三级地址联动回调
    getpickerParentValue(e) {
      // 将需要绑定的地址设置为空，并赋值
      this.form.consigneeAddressIdPath = [];
      this.form.consigneeAddressPath = [];
      let name = "";

      e.forEach((item, index) => {
        if (item.id) {
          // 遍历数据
          this.form.consigneeAddressIdPath.push(item.id);
          this.form.consigneeAddressPath.push(item.localName);
          name += item.localName;
          this.form.___path = name;
        }
        if (index == e.length - 1) {
          //如果是最后一个
          let _town = item.children.filter((_child) => {
            return _child.id == item.id;
          });

          this.form.lat = _town[0].center.split(",")[1];
          this.form.lon = _town[0].center.split(",")[0];
        }
      });
    },
	showBusiness(){
		this.businessShow = true;
	},
    // 显示三级地址联动
    showPicker() {
      this.$refs.cityPicker.show();
    },
	//显示时间
	showTime(type){
		this.show = true;
		this.time = type;
	}
  },
  mounted() {
	  // this.getBusinessData();
  },
  data() {
    return {
      lightColor: this.$lightColor, //高亮颜色
      mapFlag: false, // 地图选择开
      routerVal: "",
	  nickName:"",
	  business:"",
	  earliest:"",
	  time:'0',
	  face:"",
	  action: upload,
	  atlatest:"",
	  show: false,
	  businessShow:false,
	  businesslist: [],
	  sourcetype:['camera'],
	  header:{
		  accessToken: storage.getAccessToken() 
	  },
	  params: {
		year: false,
		month: false,
		day: false,
		hour: true,
		minute: true,
		second: false,
		minutes:['0','30']
	  },
	  type: 'select',
	  src:"/static/0830223425.png",
      form: {
        detail: "", //地址详情
        nickName: "", //收货人姓名
		contacts:"",
        face: "", //手机号码
		business:"",
		earliest:"",
		atlatest:"",
		city:"",
		id:"",
		username:"",
        consigneeAddressIdPath: [], //地址id
        consigneeAddressPath: [], //地址名字
        ___path: "", //所在区域
      },
      // 表单提交校验规则
      rules: {
        nickName: [
          {
            required: true,
            message: "门店名称不能为空",
            trigger: ["blur", "change"],
          },
        ],
        face: [
          {
            required: true,
            message: "请拍门头照",
            trigger: ["blur", "change"],
          },
        ],
		business: [
		  {
		    required: true,
		    message: "请选择经营类型",
		    trigger: ["change"],
		  },
		],
		contacts:[
			{
			  required: true,
			  message: "联系人不能为空",
			  trigger: ["blur", "change"],
			},
		],
        ___path: [
          {
            required: true,
            message: "请选择所在区域",
            trigger: ["change"],
          },
        ],
        detail: [
          {
            required: true,
            message: "请填写详细地址",
            trigger: ["blur", "change"],
          },
        ],
		earliest: [
		  {
		    required: true,
		    message: "最早收货时间不能为空",
		    trigger: ["blur", "change"],
		  },
		],
		atlatest: [
		  {
		    required: true,
		    message: "最晚收货时间不能为空",
		    trigger: ["blur", "change"],
		  },
		],
      },
      list: [
        {
          id: "",
          localName: "请选择",
          children: [],
        },
      ],
    };
  },
  onLoad(option) {
    this.routerVal = option;
	this.form.id = option.id;
	this.form.username= option.username;
	this.getBusinessData();
  },
  // 初始化rules必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
};
</script>
<style scoped lang="scss">
.detailAddress {
  /deep/ .u-form-item--left {
    display: flex;
    align-items: flex-start;
  }
}
.saveBtn,
.selectAddress {
  height: 70rpx;

  line-height: 70rpx;
  text-align: center;
  font-size: 30rpx;
  background: $aider-light-color;
  color: #fff;
  width: 70%;
  margin: 40rpx auto 0 auto;
  border-radius: 20rpx;
}
.selectAddress {
  margin-top: 40rpx;
  background: #fff;

  color: $aider-light-color;
  border: 2rpx solid $aider-light-color;
}

.uForm {
  width: 94%;
  overflow: hidden;
  left: 3%;
  position: relative;
  top: 2%;
  background: #fff;
  border-radius: 20rpx;
  padding: 0 0 40rpx 0;
}
.add-address {
  width: 100%;
  padding-top: 3%;

  /deep/ .u-form-item {
    background-color: #fff;
    padding: 24rpx 30rpx;
  }
  .u-btn {
    margin: 30rpx 30rpx 0 30rpx;
    background-color: $main-color;
  }

  /deep/.u-checkbox {
    margin: 30rpx 30rpx 0 30rpx;

    .u-label-class.u-checkbox__label {
      color: $font-color-light;
      font-size: $font-sm;
    }
  }
}
/deep/ .u-checkbox__label {
  font-size: 28rpx;
}
</style>
